﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace VisionCloud.Utility.Extensions
{
    /// <summary>
    /// Datatable扩展方法
    /// </summary>
    public static class DatatableExtensions
    {
        public static IList<T> ToList<T>(this DataTable dt)
        {
            var lst = new List<T>();
            var plist = new List<System.Reflection.PropertyInfo>(typeof(T).GetProperties());
            foreach (DataRow item in dt.Rows)
            {
                T t = System.Activator.CreateInstance<T>();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                    if (info != null)
                    {
                        if (!Convert.IsDBNull(item[i]))
                        {
                            info.SetValue(t, item[i], null);
                        }
                    }
                }
                lst.Add(t);
            }
            return lst;
        }
    }
}